/**
 * 分类管理 Composable
 * 提供分类的状态管理和API交互功能
 */
import { ref, reactive, computed } from 'vue'
import { classifyApi } from '../api/client'
import type { Classify, CreateClassifyInput, UpdateClassifyInput, ClassifyQuery, ClassifyOperationResult } from '../types/classify'

/**
 * 分类管理状态
 */
interface ClassifyState {
  classifies: Classify[]
  loading: boolean
  error: string | null
  pagination: {
    page: number
    limit: number
    total: number
    totalPages: number
  }
}

/**
 * 分类管理 Composable
 * @returns 分类管理相关的状态和方法
 */
export function useClassifies() {
  // 状态管理
  const state = reactive<ClassifyState>({
    classifies: [],
    loading: false,
    error: null,
    pagination: {
      page: 1,
      limit: 10,
      total: 0,
      totalPages: 0
    }
  })

  // 计算属性
  const hasError = computed(() => !!state.error)
  const isEmpty = computed(() => state.classifies.length === 0)
  const hasMore = computed(() => state.pagination.page < state.pagination.totalPages)

  /**
   * 清除错误信息
   */
  const clearError = () => {
    state.error = null
  }

  /**
   * 设置错误信息
   * @param error 错误信息
   */
  const setError = (error: string) => {
    state.error = error
  }

  /**
   * 获取分类列表
   * @param query 查询参数
   * @returns 操作结果
   */
  const fetchClassifies = async (query?: ClassifyQuery): Promise<ClassifyOperationResult> => {
    try {
      state.loading = true
      clearError()
      
      const response = await classifyApi.getAll(query)
      
      if (response.success) {
        state.classifies = response.data || []
        if (response.pagination) {
          state.pagination = response.pagination
        }
        return { success: true }
      } else {
        const errorMsg = response.message || '获取分类列表失败'
        setError(errorMsg)
        return { success: false, error: errorMsg }
      }
    } catch (error) {
      console.error('获取分类列表失败:', error)
      const errorMsg = '获取分类列表失败，请稍后重试'
      setError(errorMsg)
      return { success: false, error: errorMsg }
    } finally {
      state.loading = false
    }
  }

  /**
   * 根据ID获取分类
   * @param id 分类ID
   * @returns 分类详情
   */
  const fetchClassifyById = async (id: string): Promise<Classify | null> => {
    try {
      clearError()
      
      const response = await classifyApi.getById(id)
      
      if (response.success && response.data) {
        return response.data
      } else {
        setError(response.message || '获取分类详情失败')
        return null
      }
    } catch (error) {
      console.error('获取分类详情失败:', error)
      setError('获取分类详情失败，请稍后重试')
      return null
    }
  }

  /**
   * 创建分类
   * @param data 分类数据
   * @returns 操作结果
   */
  const createClassify = async (data: CreateClassifyInput): Promise<ClassifyOperationResult> => {
    try {
      clearError()
      
      const response = await classifyApi.create(data)
      
      if (response.success && response.data) {
        // 添加到本地状态
        state.classifies.unshift(response.data)
        state.pagination.total += 1
        return { success: true, data: response.data }
      } else {
        const errorMsg = response.message || '创建分类失败'
        setError(errorMsg)
        return { success: false, error: errorMsg }
      }
    } catch (error) {
      console.error('创建分类失败:', error)
      const errorMsg = '创建分类失败，请稍后重试'
      setError(errorMsg)
      return { success: false, error: errorMsg }
    }
  }

  /**
   * 更新分类
   * @param id 分类ID
   * @param data 更新数据
   * @returns 操作结果
   */
  const updateClassify = async (id: string, data: UpdateClassifyInput): Promise<ClassifyOperationResult> => {
    try {
      clearError()
      
      const response = await classifyApi.update(id, data)
      
      if (response.success && response.data) {
        // 更新本地状态
        const index = state.classifies.findIndex(classify => classify.id === id)
        if (index !== -1) {
          state.classifies[index] = response.data
        }
        return { success: true, data: response.data }
      } else {
        const errorMsg = response.message || '更新分类失败'
        setError(errorMsg)
        return { success: false, error: errorMsg }
      }
    } catch (error) {
      console.error('更新分类失败:', error)
      const errorMsg = '更新分类失败，请稍后重试'
      setError(errorMsg)
      return { success: false, error: errorMsg }
    }
  }

  /**
   * 删除分类
   * @param id 分类ID
   * @returns 操作结果
   */
  const deleteClassify = async (id: string): Promise<ClassifyOperationResult> => {
    try {
      clearError()
      
      const response = await classifyApi.delete(id)
      
      if (response.success) {
        // 从本地状态中移除
        const index = state.classifies.findIndex(classify => classify.id === id)
        if (index !== -1) {
          state.classifies.splice(index, 1)
          state.pagination.total -= 1
        }
        return { success: true }
      } else {
        const errorMsg = response.message || '删除分类失败'
        setError(errorMsg)
        return { success: false, error: errorMsg }
      }
    } catch (error) {
      console.error('删除分类失败:', error)
      const errorMsg = '删除分类失败，请稍后重试'
      setError(errorMsg)
      return { success: false, error: errorMsg }
    }
  }

  /**
   * 刷新分类列表
   */
  const refreshClassifies = () => {
    fetchClassifies()
  }

  /**
   * 重置状态
   */
  const resetState = () => {
    state.classifies = []
    state.loading = false
    state.error = null
    state.pagination = {
      page: 1,
      limit: 10,
      total: 0,
      totalPages: 0
    }
  }

  return {
    // 状态
    state,
    classifies: computed(() => state.classifies),
    loading: computed(() => state.loading),
    error: computed(() => state.error),
    pagination: computed(() => state.pagination),
    
    // 计算属性
    hasError,
    isEmpty,
    hasMore,
    
    // 方法
    fetchClassifies,
    fetchClassifyById,
    createClassify,
    updateClassify,
    deleteClassify,
    refreshClassifies,
    resetState,
    clearError,
    setError
  }
}